<?php

namespace app\api\controller\v47;

use app\api\controller\v2\Auth;
use app\common\cachemodel\chat\HzChatLastSendTimeRecord;
use app\common\cachemodel\chat\HzChatRecord;
use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\lib\Aes;
use app\common\lib\Util;
use app\common\model\Recode;
use app\common\service\ChatParse;
use think\Cache;

class AiUserChat extends Auth
{
    public function getStatusMsg()
    {
        $rid = input('rid/d', 0);
        $type = input('type/d', 0);
        if (!$rid || !in_array($type, [1, 2, 3, 4], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
        if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'] || $recodeInfo['status'] != 1)
        {
            return show(config('code.error'), '档案不存在');
        }

        switch ($type)
        {
            case 2:
                $callTextType = 102;
                break;
            case 3:
                $callTextType = 103;
                break;
            case 4:
                $callTextType = 104;
                break;
            default:
                $inSign = explode('-', $recodeInfo['sun'])[0];
                $callTextType = (int)$inSign;
        }
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);

        return show(config('code.success'), '请求成功', [
            'content' => $hzChatRecordDetailsModel->defaultCallContent[$callTextType],
            'num' => $numData['res_num'],
        ]);
    }

    public function insertStatusMsg()
    {
        $rid = input('rid/d', 0);
        $type = input('type/d', 0);
        if (!$rid || !in_array($type, [1, 2, 3, 4], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'insertStatusMsg', 'type' => $type, 'rid' => $rid], 5) && (int)$this->user['id'] != 10834769)
        {//mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
        if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'] || $recodeInfo['status'] != 1)
        {
            return show(config('code.error'), '档案不存在');
        }
        $hzChatRecordModel = new HzChatRecord();
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        // 通过rid 取当前会话ID
        if ($rid)
        {
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }
        if (!$chatId)
        {
            return show(config('code.error'), '服务异常，请刷新页面重试～');
        }
        switch ($type)
        {
            case 2:
                $callTextType = 102;
                break;
            case 3:
                $callTextType = 103;
                break;
            case 4:
                $callTextType = 104;
                break;
            default:
                $inSign = explode('-', $recodeInfo['sun'])[0];
                $callTextType = (int)$inSign;
        }
        $nowTimw = $this->request->time();
        $insertData = [
            [   // 用户提问消息
                'chat_id' => $chatId,
                'uid' => $this->user['id'],
                'rid' => $rid,
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => $hzChatRecordDetailsModel->defaultCallContent[$callTextType], // 提问问题
                'data_type' => 1,
                'extend' => ['is_call' => 1, 'call_text_type' => $callTextType],  // call_text_type = 0 表示 随机内容 非固定文案
                'result_data' => '',
                'option_id' => '',
                'pid' => 0,
                'create_time' => $nowTimw,
            ],
        ];
        $resData = $hzChatRecordDetailsModel->SaveData($chatId, $insertData);
        if ($resData)
        {   // 发送成功
            // 更新 用户 最后发送消息 时间
            (new HzChatLastSendTimeRecord())->UpdateData($this->user['id'], ['last_send_time' => $nowTimw]);
            $chatDetailId = $resData[0]['id'];
            $hzChatRecordModel->updateData($chatId, $this->user['id'], [
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $nowTimw,
            ]);
            $resData = $hzChatRecordDetailsModel->dataListResert($resData, true);
            $resData[0]['create_time'] = '';
            $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
            $resData[0]['num'] = $numData['res_num'];
            $resData[0]['input_text'] = $hzChatRecordDetailsModel->getInputPlaceholder($numData);

            return show(config('code.success'), '请求成功', $resData[0]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    public function getChatTts()
    {
        $chatDetailId = input('chat_id/d', 0);
        $text = input('text/s', '');
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $key = array_search($text, $hzChatRecordDetailsModel->defaultCallContent);
        if ($key !== false)
        {
            $fileName = APP_PATH . 'common/resource/' . $key . '.mp3';
            if (file_exists($fileName))
            {
                $content = file_get_contents($fileName);
                ChatParse::sendVoice($content);
                return;
            }
            if ($text)
            {
                ChatParse::getChatTTS([
                    'text' => $text,
                    'uid' => $this->user['id'],
                ]);
                return;
            }
        }
        if (!$chatDetailId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        //验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['action' => 'getChatVoice', 'chat_detail_id' => $chatDetailId, 'text' => $text], 2))
        {
            return show(config('code.error'), '别心急，等一等');
        }
        $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
        if (!$chatDetailInfo || $chatDetailInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        if (isset($chatDetailInfo['extend']['call_text_type']) && $chatDetailInfo['extend']['call_text_type'])
        {
            $fileName = APP_PATH . 'common/resource/' . $chatDetailInfo['extend']['call_text_type'] . '.mp3';
            if (file_exists($fileName))
            {
                $content = file_get_contents($fileName);
                ChatParse::sendVoice($content);
                return;
            }
        }
        if (empty($chatDetailInfo['content']) && empty($text))
        {
            return;
        }
        if ($chatDetailInfo['content'] && empty($text))
        {
            $text = $chatDetailInfo['content'];
        } else
        {
            // if ($chatDetailInfo['content'] && strpos($chatDetailInfo['content'], $text) === false)
            // {
            //     return show(config('code.error'), '服务异常，请稍后再试～');
            // }
        }
        // $key = array_search($text, $hzChatRecordDetailsModel->defaultCallContent);
        // if ($key !== false)
        // {
        //     $fileName = APP_PATH . 'common/resource/' . $key . '.mp3';
        //     if (file_exists($fileName))
        //     {
        //         $content = file_get_contents($fileName);
        //         ChatParse::sendVoice($content);
        //         return;
        //     }
        // }
        if ($text)
        {
            $res = ChatParse::getChatTTS([
                'text' => $text,
                'uid' => $this->user['id'],
            ]);
        }
    }

    public function getSttToken()
    {
        // 智能语音交互
        // ram用户：zhinengyuyinjiaohu@goddessxzns.onaliyun.com
        // AccessKey ID:LTAI5t9G89fRkd2zZqpThXAN
        // AccessKey Secret:TWVT5cgSCW2DK3sp2FDfTd6BRkoeAj
        //
        // 准了beta 项目Appkey
        // QVzI8no79zGfHvYI
        // 准了线上 项目Appkey
        // j5b6FumQP0I16nGY
        $cacheToken = 'zhunle:stt:openapi:token';
        $token = Cache::get($cacheToken, false);
        if (!$token)
        {
            $AccessKeyId = 'LTAI5t9G89fRkd2zZqpThXAN';
            $AccessKeySecret = 'TWVT5cgSCW2DK3sp2FDfTd6BRkoeAj';
            date_default_timezone_set('UTC');
            $params = [
                'AccessKeyId' => $AccessKeyId,    // 阿里云账号AccessKey ID
                'Action' => 'CreateToken',  // POP API名称：CreateToken
                'Version' => '2019-02-28',  // POP API版本：2019-02-28
                'Format' => 'JSON',         // 响应返回的类型：JSON
                'RegionId' => 'cn-beijing',    // 服务所在的地域ID：cn-shanghai
                'Timestamp' => date("Y-m-d\TH:i:s\Z"),  // 请求的时间戳。日期格式按照ISO 8601标准表示，且使用UTC时间，时区：+0。格式：YYYY-MM-DDThh:mm:ssZ。如2019-04-03T06:15:03Z为UTC时间2019年4月3日6点15分03秒。
                'SignatureMethod' => 'HMAC-SHA1',   // 签名算法：HMAC-SHA1
                'SignatureVersion' => '1.0',    // 签名算法版本：1.0
                'SignatureNonce' => strtolower(uuid(microtime(true) . mt_rand(0, 99999))), // 随机字符串 唯一随机数uuid，用于请求的防重放攻击，每次请求唯一，不能重复使用。格式为A-B-C-D-E（A、B、C、D、E的字符位数分别为8、4、4、4、12）。例如，8d1e6a7a-f44e-40d5-aedb-fe4a1c80f434。
            ];
            ksort($params);
            $url = 'http://nls-meta.cn-shanghai.aliyuncs.com/';
            $paramsStr = http_build_query($params);
            $sign = base64_encode(hash_hmac('sha1', "GET&%2F&" . urlencode($paramsStr), $AccessKeySecret . '&', true));;
            $signUrl = urlencode($sign);
            $params['Signature'] = $signUrl;
            $url .= "?Signature={$signUrl}&$paramsStr";
            $data = Util::curlRequest("GET", $url);
            $data = json_decode($data, true);
            $token = $data['Token']['Id'] ?? '';
            if (empty($token))
            {
                return show(config('code.error'), '服务异常，语音服务连接失败');
            }
            // 设置缓存 1天有效期
            Cache::set($cacheToken, $token, 86400);
        }
        if (Util::isOnline())
        {   // 准了线上 项目Appkey
            // j5b6FumQP0I16nGY
            $appKey = 'j5b6FumQP0I16nGY';
        } else
        {   // 准了beta 项目Appkey
            // QVzI8no79zGfHvYI
            $appKey = 'QVzI8no79zGfHvYI';
        }
        $resData = [
            'token' => (new Aes())->encryptWithOpenssl($token),
            'app_key' => $appKey,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }
}